import React, { useCallback, useEffect } from 'react';
import { Modal, Button, Form, Input, Space, Image } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import UploadOSS from '@/components/UploadOSS';

const wrapperCol = { offset: 8, span: 16 };

interface AddOrEditProps {
  isModalVisible: boolean;
  onCancelWrite: () => void;
  flag: string;
  onSubmit: (valuse: any) => void;
  sliceData: any;
}

const AddOrEdit: React.FC<AddOrEditProps> = ({
  isModalVisible,
  onCancelWrite,
  flag,
  onSubmit,
  sliceData,
}) => {
  const [form] = Form.useForm();

  const handleCancel = useCallback(() => {
    onCancelWrite();
    form.resetFields();
  }, [onCancelWrite, form]);

  const handleSetFilesURL = useCallback(
    (url) => {
      form.setFieldsValue({ img: url });
    },
    [form],
  );

  const handleFinsh = useCallback(
    (values) => {
      onSubmit(values);
    },
    [onSubmit],
  );

  const handleReset = useCallback(() => {
    form.resetFields();
  }, [form]);

  useEffect(() => {
    if (flag === 'edit') {
      form.setFieldsValue(sliceData);
    } else if (flag === 'add') {
      form.resetFields();
    }
  }, [flag, form, sliceData]);

  return (
    <Modal
      title={flag === 'add' ? '添加轮播' : '编辑轮播'}
      visible={isModalVisible}
      onCancel={handleCancel}
      footer={null}
      forceRender={true}
      destroyOnClose={true}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleFinsh}
        preserve={false}
      >
        <Form.Item
          label="轮播名"
          name="title"
          rules={[{ required: true, message: '请输入轮播名' }]}
        >
          <Input placeholder="请输入轮播名" />
        </Form.Item>

        <Form.Item label="跳转的URL" name="url">
          <Input placeholder="请输入跳转的url" />
        </Form.Item>

        <Form.Item label="排序" name="seq">
          <Input placeholder="请输入排序" />
        </Form.Item>

        <Form.Item
          label="轮播图"
          name="img"
          rules={[{ required: true, message: '请上传' }]}
        >
          <UploadOSS
            accept="image/*"
            listType="picture"
            maxCount={1}
            showUploadList={true}
            onSetFilesURL={handleSetFilesURL}
            isModalVisible={isModalVisible}
          >
            <Button icon={<UploadOutlined />}>请选择轮播图</Button>
          </UploadOSS>
        </Form.Item>

        {<Input name="img" hidden={true} />}

        {flag === 'edit' ? (
          <Form.Item label="当前轮播图" name="current">
            <Image src={sliceData?.img_url} />
          </Form.Item>
        ) : (
          ''
        )}

        <Form.Item wrapperCol={wrapperCol}>
          <Space>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddOrEdit;
